﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Net;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Documents;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Media.Animation;
using System.Windows.Shapes;
using Microsoft.Phone.Controls;
using Microsoft.Phone.Shell;
using System.Windows.Media.Imaging;
using MTGScore_Cards.Resources;

namespace MTGScore_Cards
{
    public partial class CardPage : PhoneApplicationPage
    {
        public CardPage()
        {
            InitializeComponent();
        }
        Card card;
        bool isTrial;
        private void CardPage_Loaded(object sender, RoutedEventArgs e)
        {
            object o;
            if (!PhoneApplicationService.Current.State.TryGetValue("SelectedCard", out o))
            {
                NavigationService.GoBack();
                return;
            }
            card = (Card)o;
            isTrial = App.isTrial();
            BuildScreen();
            DisableProgressBar();
            
            SetTrialMode();
        }
        void SetTrialMode()
        {
            if (isTrial)
            {
                Grid.SetRowSpan(ScrollViewer, 1);
                
            }
            else
            {
                AdControl.Visibility = System.Windows.Visibility.Collapsed;
                AdGrid.Visibility = System.Windows.Visibility.Collapsed;
                Grid.SetRowSpan(ScrollViewer, 3);
                Grid.SetRow(ToggleProgressBar, 2);
                
            }
        }
        private void SetImage(string url)
        {
            Image.Source = new BitmapImage(new Uri(url, UriKind.RelativeOrAbsolute));
        }
        private void ApplicationBarMenuButton_Click(object sender, EventArgs e)
        {
            //ApplicationBarMenuItem
            try
            {
                var item = (ApplicationBarMenuItem)sender;

                for (int i = 0; i < card.edictions.Count; i++)
                    if (card.edictions[i].name == item.Text)
                    {
                        //SetImage(card.languages[i].image);
                        SearchDetails(card.edictions[i].url);
                        //Name_TextBox.Text = card.languages[i].name;
                        break;
                    }

                for (int i = 0; i < card.languages.Count; i++)
                    if (card.languages[i].name == item.Text)
                    {
                        //SetImage(card.languages[i].image);
                        SearchDetails(card.languages[i].url);
                        //Name_TextBox.Text = card.languages[i].name;
                        break;
                    }
            }
            catch (Exception ex)
            {
                ex.ToString();
            }
        }

        public void BuildScreen()
        {

            Name_TextBox.Text = card.name;
            Type_TextBox.Text = card.type;
            Text_TextBox.Text = card.text;// +"\n" + card.text + card.text + card.text + card.text + card.text + card.text + card.text + card.text + card.text;
            CCC_TextBox.Text = card.ccc;
            CC_TextBox.Text = card.cc;
            SetImage(card.image);

            Faqs_List.Items.Clear();
            if (card.faqs.Count == 0)
            {
                Faqs_Text.Visibility = System.Windows.Visibility.Collapsed;
                Faqs_Interline.Visibility = System.Windows.Visibility.Collapsed;
            }
            else
            {
                Faqs_Text.Visibility = System.Windows.Visibility.Visible;
                Faqs_Interline.Visibility = System.Windows.Visibility.Visible;
            }
            for (int i = 0; i < card.faqs.Count; i++)
            {
                Faqs_List.Items.Add(new TextBlock() { Text = card.faqs[i] , FontSize = 18, TextWrapping = TextWrapping.Wrap});
            }


            Legals_List.Items.Clear();

            if (card.legals.Count == 0)
            {
                Legals_Text.Visibility = System.Windows.Visibility.Collapsed;
                Legals_Interline.Visibility = System.Windows.Visibility.Collapsed;
            }
            else
            {
                Legals_Text.Visibility = System.Windows.Visibility.Visible;
                Legals_Interline.Visibility = System.Windows.Visibility.Visible;
            }
            for (int i = 0; i < card.legals.Count; i++)
            {
                Legals_List.Items.Add(new TextBlock() { Text = card.legals[i], FontSize = 18, TextWrapping = TextWrapping.Wrap });
            }
            if (isTrial || (card.languages.Count == 1 && card.edictions.Count==1))
            {
                ApplicationBar.IsMenuEnabled = false;
                ApplicationBar.IsVisible = false;
            }
            else
            {
                ApplicationBar.MenuItems.Clear();
                if(card.edictions.Count>0)
                    ApplicationBar.MenuItems.Add(new ApplicationBarMenuItem(Strings.Editions));
                for (int i = 0; i < card.edictions.Count; i++)
                {

                    if (card.edictions[i].name == "")
                        card.edictions[i].name = "Unknown";
                    var b = new ApplicationBarMenuItem(card.edictions[i].name);
                    b.Click += ApplicationBarMenuButton_Click;
                    ApplicationBar.MenuItems.Add(b);
                }
                if (card.languages.Count > 0)
                    ApplicationBar.MenuItems.Add(new ApplicationBarMenuItem(Strings.Languages));
                for (int i = 0; i < card.languages.Count; i++)
                {
                    
                    if (card.languages[i].name == "")
                        card.languages[i].name = "Unknown";
                    var b = new ApplicationBarMenuItem(card.languages[i].name);
                    b.Click += ApplicationBarMenuButton_Click;
                    ApplicationBar.MenuItems.Add(b);
                }
            }
            ScrollViewer.ScrollToVerticalOffset(0);
        }

        #region ACTIVATE_DEACTIVATE

        protected override void OnNavigatedTo(System.Windows.Navigation.NavigationEventArgs e)
        {

            base.OnNavigatedFrom(e);

            if (this.State.ContainsKey("MTGSCore_CurrentCard"))
            {

                card = (Card)(this.State["MTGSCore_CurrentCard"]);

                this.State.Remove("MTGSCore_CurrentCard");

            }
        }


        protected override void OnNavigatedFrom(System.Windows.Navigation.NavigationEventArgs e)
        {

            base.OnNavigatedTo(e);

            this.State.Add("MTGSCore_CurrentCard", card);
        }


        #endregion

        private void Faqs_List_SelectionChanged(object sender, SelectionChangedEventArgs e)
        {
            Faqs_List.SelectedItem = null;
        }

        private void Legals_List_SelectionChanged(object sender, SelectionChangedEventArgs e)
        {
            Legals_List. SelectedItem = null;
        }


        private void SearchDetails(string arg)
        {

            var current_query = "http://venetomagic.altervista.org/magic/magic_result2_details.php?url_details=" + arg;
            Research.getHTML(current_query, GotHTML, ErrorGettingHTML);
            Dispatcher.BeginInvoke(() => EnableProgressBar());
        }
        
        private void GotHTML(string html)
        {
            try
            {
                var currentResult = new ResultsParser(html).GetResults();
                if (currentResult.cards == null || currentResult.cards.Count == 0)
                {
                    ErrorGettingHTML();
                    return;
                }
                card = currentResult.cards[0];
                Dispatcher.BeginInvoke(() => BuildScreen());
            }
            catch (Exception e)
            {
                e.ToString();
            }
            finally
            {
                Dispatcher.BeginInvoke(() => DisableProgressBar());
            }
        }
        private void EnableProgressBar()
        {
            if(isTrial)
                Grid.SetRowSpan(ScrollViewer, 1);
            else
                Grid.SetRowSpan(ScrollViewer, 2);
            ToggleProgressBar.IsEnabled = true;
            ToggleProgressBar.IsIndeterminate = true;
            ToggleProgressBar.Visibility = System.Windows.Visibility.Visible;
        }
        private void DisableProgressBar()
        {
            if(isTrial)
                Grid.SetRowSpan(ScrollViewer, 2);
            else
                Grid.SetRowSpan(ScrollViewer, 3);
            ToggleProgressBar.IsEnabled = false;
            ToggleProgressBar.IsIndeterminate = false;
            ToggleProgressBar.Visibility = System.Windows.Visibility.Collapsed;
        }
        private void ErrorGettingHTML()
        {
            //ToggleProgressBar.IsEnabled = false;
            //ToggleProgressBar.IsIndeterminate = false;
            //ToggleProgressBar.Visibility = System.Windows.Visibility.Collapsed;
            Dispatcher.BeginInvoke(() =>
            {
                MessageBox.Show(Strings.ErrorGettingData);
                DisableProgressBar();
            });
        }

        private void Ads_Button_Click(object sender, RoutedEventArgs e)
        {
            MainPage.showProducts = true;
            NavigationService.GoBack();
        }

        private void AdControl_AdControlError(object sender, Microsoft.Advertising.Mobile.UI.ErrorEventArgs e)
        {
            //AdControl.Visibility = System.Windows.Visibility.Collapsed;
            //AdGrid.Visibility = System.Windows.Visibility.Collapsed;
            if(App.isTrial())
                Dispatcher.BeginInvoke(() =>
                {
                    Ads_Button.Visibility = System.Windows.Visibility.Visible;
                });
        }
    }
}